package com.xingshang.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingshang.model.po.*;
import com.xingshang.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private CartService cartService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressService addressService;


    @GetMapping("/user")
    public String myOrder(Model model, HttpSession session, @RequestParam(defaultValue = "1") Integer page) {
        User user = (User) session.getAttribute("user");

        //限制5条
        int pageSize = 5;  // 每页5条
        Page<Order> orderPage = new Page<>(page, pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>()
                .eq("user_id", user.getId())
                .orderByDesc("add_time");
        IPage<Order> resultPage = orderService.page(orderPage, wrapper);
//        List<Order> orders = orderService.list(
//                new QueryWrapper<Order>()
//                        .eq("user_id", user.getId())
//                        .last("LIMIT 5") //
//        );

//        List<Order> orders = orderService.findByUserId(user.getId());
        List<Order> orders = resultPage.getRecords();
        List<Map<String, Object>> orderGroups = new ArrayList<>();

        for (Order order : orders) {
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("no", order.getNo());
            orderMap.put("addTime", order.getAddTime());
            orderMap.put("status", order.getStatus());
            orderMap.put("totalMoney", order.getTotalMoney());
            orderMap.put("address", order.getAddress());
            orderMap.put("accept", order.getAccept());
            orderMap.put("telphone", order.getTelphone());

            // 改为从订单项获取商品信息，而不是从购物车
            List<OrderItem> orderItems = orderItemService.findByOrderId(order.getId());

            List<Map<String, Object>> items = new ArrayList<>();
            for (OrderItem item : orderItems) {
                Map<String, Object> itemMap = new HashMap<>();
                itemMap.put("image", item.getImage());
                itemMap.put("name", item.getName());
                itemMap.put("price", item.getPrice());
                itemMap.put("goodsId", item.getGoodsId());
                itemMap.put("quantity", item.getNum());
                items.add(itemMap);
            }

            orderMap.put("items", items); // 放入商品列表
            orderGroups.add(orderMap);
        }

        model.addAttribute("orderGroups", orderGroups); // 供 JSP 使用
        model.addAttribute("page", resultPage.getCurrent());   // 当前页码
        model.addAttribute("totalPages", resultPage.getPages());      // 总页数
//        model.addAttribute("totalItems", resultPage.getTotal());      // 总记录数
        return "orders"; // 返回到 orders.jsp 页面
    }

    @GetMapping("/addItem")
    public String addItemToCart(
            @RequestParam("id") Integer goodsId,
            @RequestParam("num") Integer quantity,
            HttpSession session,
            RedirectAttributes redirectAttributes) {

        // 1. 用户登录验证
        User user = (User) session.getAttribute("user");

        // 2. 校验商品是否存在
        Goods goods = goodsService.getById(goodsId);
        if (goods == null) {
            redirectAttributes.addFlashAttribute("msg", "商品不存在");
            return "redirect:/error";
        }

        // 3. 校验数量合法性
        if (quantity <= 0) {
            redirectAttributes.addFlashAttribute("msg", "商品数量必须大于0");
            return "redirect:/goods/" + goodsId;
        }

        // 4. 获取用户当前购物车（含逻辑删除的记录）
        Cart cartItem = cartService.getCartItemByUserIdAndGoodsId(user.getId(), goodsId);

        if (cartItem != null) {
            if ("Y".equals(cartItem.getIsDelete())) {
                // 如果是逻辑删除状态，则恢复并更新数量
                cartItem.setIsDelete("N");
                cartItem.setQuantity(quantity); // 重新设置为新加的数量
            } else {
                // 已存在则累加数量
                cartItem.setQuantity(cartItem.getQuantity() + quantity);
            }
            cartItem.setUpdateTime(new Date(System.currentTimeMillis()));
            cartService.updateCartItem(cartItem); // 更新购物车记录
        } else {
            // 不存在则创建新记录
            Cart newCartItem = new Cart();
            newCartItem.setUserId(user.getId());
            newCartItem.setGoodsId(goodsId);
            newCartItem.setQuantity(quantity);
            newCartItem.setIsDelete("N");
            newCartItem.setCreateTime(new Date(System.currentTimeMillis()));
            newCartItem.setUpdateTime(new Date(System.currentTimeMillis()));
            cartService.addCartItem(newCartItem);
        }

        redirectAttributes.addFlashAttribute("msg", "商品已成功加入购物车");
        return "redirect:/order/submit";
    }


    @PostMapping("/submit")
    public String createOrder(
            HttpSession session,
            Model model,
            @RequestParam("addressId") Integer addressId,
            @RequestParam("payType") Integer payType,

            // 发票相关参数
            @RequestParam(name = "type", required = false) String invoiceType,
            @RequestParam(name = "title", required = false) String title,
            @RequestParam(name = "taxId", required = false) String taxId,
            @RequestParam(name = "bankCard", required = false) String bankCard,
            RedirectAttributes redirectAttributes) throws Exception {

        User user = (User) session.getAttribute("user");
        Order order = orderService.submitOrder(user.getId(), addressId, user.getTelphone(), payType, session, invoiceType, title, taxId, bankCard);
        System.out.println("order = " + order);
        model.addAttribute("OrderNo", order.getNo());
        model.addAttribute("order", order);
        model.addAttribute("totalPrice", order.getTotalMoney());
        model.addAttribute("payType", payType);
        return "order_submit";

    }


    @GetMapping("/add")
    public String submitOrder(Model model, HttpSession session) {
        System.out.println("提交订单");
        User user = (User) session.getAttribute("user");
        Admin adminNew = adminService.findByAccount(user.getAccount());
        if (user == null || adminNew == null) {
            session.setAttribute("admin", adminNew);
        }
        session.setAttribute("loginUser", user);
        List<Address> addresses = addressService.listByUserId(user.getId());
//        List<Address> addresses = addressService.listByUserId(2);
        model.addAttribute("addresses", addresses);
        List<Cart> cartList = cartService.getCartByUserId(user.getId());
        List<Cart> cartList1 = cartService.findGoodsByCart(cartList);
        model.addAttribute("cartItems", cartList1);
        model.addAttribute("money", cartList1.stream().mapToDouble(cart -> cart.getSalePrice().doubleValue() * cart.getQuantity()).sum());
//        System.out.println(addresses);
//
//        System.out.println(addressService.list());

        return "order_add";
    }

    //支付
    @PostMapping("/pay/now")
    @ResponseBody
    public String payOrder(String orderNo, HttpSession session, String orderId) {
        User user = (User) session.getAttribute("loginUser");

        Integer userId = user.getId();
        System.out.println("orderIde：" + orderId);
        return orderService.payOrder(userId, orderNo, session, orderId);
    }


    //进入支付是否成功页面
    @GetMapping("/alipay/return")
    public String returnOrder(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        String orderNo = session.getAttribute("orderNo").toString();
        String orderId = session.getAttribute("orderId").toString();
        if (orderNo == null || "".equals(orderNo)) {
            return "redirect:/cart";
        }
        Integer userId = user.getId();
        //模拟结算订单
        orderService.orderSuccess(orderNo, userId, orderId);
        return "pay_suc";
    }

}
